package com.example.hosptial.newController;

import com.example.hosptial.model.enity.Admin;
import com.example.hosptial.service.AuthService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 主页控制器
 * 处理根路径访问和管理员页面路由
 */
@Controller
public class HomeController {

    @Autowired
    private AuthService authService;

    /**
     * 处理根路径访问
     * 重定向到登录页面
     */
    @GetMapping("/")
    public String home() {
        return "redirect:/admin/auth/login";
    }

    /**
     * 处理管理员主页访问
     */
    @GetMapping("/admin/index")
    public String adminIndex(HttpSession session, Model model, RedirectAttributes redirectAttributes) {
        // 验证管理员会话
        if (!authService.validateAdminSession(session)) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/admin/auth/login";
        }

        // 从session中获取管理员信息
        Admin admin = (Admin) session.getAttribute("admin");
        model.addAttribute("admin", admin);
        
        return "admin/index";
    }

    /**
     * 处理管理员页面片段请求
     */
    @GetMapping("/pages/admin/{page}")
    public String getAdminPage(@PathVariable String page, HttpSession session, RedirectAttributes redirectAttributes) {
        // 验证管理员会话
        if (!authService.validateAdminSession(session)) {
            redirectAttributes.addFlashAttribute("error", "请先登录");
            return "redirect:/admin/auth/login";
        }
        
        return "admin/" + page;
    }
} 